from django.conf import settings
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView,RetrieveAPIView,UpdateAPIView
from rest_framework.response import Response

from random import randint
from threading import Thread
from meiduo_mall.libs.yuntongxun.sms import CCP
from meiduo_mall.utils.exceptions import logger
from celery_tasks.sms.tasks import send_sms_code
from rest_framework.permissions import IsAuthenticated
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

# def send_sms_code(mobile,sms_code):
#     # 发送短信
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)
#
from users.models import User
from verifications.serializers import CreateUserSerializer, UserFetailSerializer, UserUpdateserializer


class SMSCodeView(APIView):
    '''
    发送短信验证码
    1. 获取前端传递的手机号，路径中进行正则匹配
    2. 生成短信验证码
    3. 保存短信验证码到缓存中
    4. 发送短信
    5. 结果返回

    '''
    def get(self, request,mobile):

        # 建立连接redis的对象
        conn = get_redis_connection('sms_code')
        # 60s内不能重复发送短信
        send_flag = conn.get('sms_code_flag_%s' % mobile)
        if send_flag:
            return Response({"message": "发送短信过于频繁"})
        # 生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)

        # 生成管道对象
        pl=conn.pipeline()
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        pl.setex('sms_code_flag_%s' % mobile, 60 , 1)
        # 连接缓存，传入数据
        pl.execute()
        # # 发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,'5'],1)
        #
        # t = Thread(target='send_sms_code',kwargs={
        #     'mobile':mobile,'sms_code':sms_code})
        # t.start()
        # t.join()

        send_sms_code.delay(mobile,sms_code)
        # 5.返回结果
        return Response({"message": "OK"})


class UsernameView(APIView):
    '''
    判断用户名数量，如果为0,则没有注册过
    '''
    def get(self,request,username):
        '''
        获取指定用户名数量
        :param request: 
        :param username: 
        :return: 
        '''
        count = User.objects.filter(username=username).count()
        
        data = {
            'username': username,
            'count': count
        }
        return Response(data)

class MobileCountView(APIView):
    # 手机号判断
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile' :mobile,
            'count': count
        }
        return Response(data)
    
class UserView(CreateAPIView):
    """
    用户注册
    """
    serializer_class = CreateUserSerializer


class UserFetailView(RetrieveAPIView):
    '''
    返回用户信息
    '''
    serializer_class = UserFetailSerializer
    # queryset = User.objects.all()
    #　用户认证权限
    permission_classes = [IsAuthenticated]
    # 重写get_object,指定返回的用户对象
    def get_object(self):
        return self.request.user

class UserUpdateView(UpdateAPIView):
    '''
    更新邮箱
    '''
    serializer_class = UserUpdateserializer
    def get_object(self):
        return self.request.user

# 邮箱验证
class EmailView(APIView):
    def get(self,request):
        # 1.获取前端数据
        token = request.query_params.get('token')
        # 2.验证数据 解密token
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return Response({'errors':'token无效'})

        # 3.查询用户
        username = data.get('name')
        user = User.objects.get(username=username)
        # 4.更新用户邮箱验证状态
        user.email_active = True
        user.save()
        # 5.返回结果
        return Response({'message':True})
